import COS from 'cos-wx-sdk-v5';
import store from '../store/index.js'



const cos = new COS({
	SecretId: 'AKIDdEnEYyLk7IF6m9RdjvEj7Pcu8E8vEXot',
	SecretKey: 'zvhU9f3Hi3IPNCtTuqjZJvOn4ExiFZfa',
});

const Bucket = 'golfren-1322973459'
const Region = 'ap-beijing'
const prefix = 'img'
const compressedFile = '/compressedFile'

export const today = () => {
	const currentDate = new Date();
	const year = currentDate.getFullYear();
	const month = String(currentDate.getMonth() + 1).padStart(2, '0');
	const day = String(currentDate.getDate()).padStart(2, '0');
	return `${year}${month}${day}`;
};

//上传图片
export const ossUploadImg = (filePath, is_toast) => {
	return new Promise((resolve, reject) => {
		const originalFileName = filePath.split('/').pop().replaceAll(',',''); // 获取原始文件名
		const timestamp = new Date().getTime(); // 获取时间戳
		const day = today()
		
		const fileName = `/compressedFile-${timestamp}-${originalFileName}`; // 生成唯一文件名
		const key = prefix + fileName
		const fileid = compressedFile + `/${timestamp}-${originalFileName}`
	
		// 设置图片处理规则（例如：压缩为 80% 质量）
		const picOperations = {
			is_pic_info: 1,
			rules: [
				{
					fileid: fileid,
					rule: 'imageMogr2/thumbnail/400x400/quality/80' // 压缩为 400x400 & 质量 80%
				}
			]
		};
		
		wx.getFileSystemManager().readFile({
			filePath: filePath,
			success(res) {
				// res.data 是一个 ArrayBuffer
		
				// 上传文件
				cos.putObject({
					Bucket,
					/* 必须 */
					Region,
					/* 必须 */
					Key: key,
					Body: res.data, // 上传文件对象，必填
					Headers: {
					  // 通过 imageMogr2 接口使用图片缩放功能：指定图片宽度为 200，宽度等比压缩
					  'Pic-Operations': JSON.stringify(picOperations),
					},
					/* 必须 */
					onProgress: function(info) {
						console.log('进度',info, JSON.stringify(info), is_toast);
						// 更新提示内容
						if(is_toast === undefined){
							uni.showToast({duration:3000,
								title: `上传中: ${Math.floor(info.percent * 100)}%`,
								icon: 'loading',
								duration: 10000, // 继续显示提示
								mask: true
							});
						}
						
					}
				}, function(err, data) {
					
					if(is_toast === undefined){
						uni.hideToast()
					}
					
					if (err) {
						console.log('上传失败',err);
						reject(err)
					} else {
						console.log('上传成功', data,store.state.oss_url , key, fileid);
						resolve({
							name: originalFileName,
							url: store.state.oss_url  + '/' +  key 
						})
					}
				});
			},
			fail(err) {
				console.error('读取文件失败:', err);
			}
		});
	
	})
}

//所有可上传  不压缩的
export const ossUpload = (filePath, is_toast) => {
	return new Promise((resolve, reject) => {
		const originalFileName = filePath.split('/').pop().replaceAll(',',''); // 获取原始文件名
		const timestamp = new Date().getTime(); // 获取时间戳
		const day = today()
		
		const fileName = `/${timestamp}-${originalFileName}`; // 生成唯一文件名
		const key = prefix  + fileName
		// 上传文件
		cos.postObject({
			Bucket,
			/* 必须 */
			Region,
			/* 必须 */
			Key: key,
			/* 必须 */
			FilePath: filePath,
			/* 必须 */
			onProgress: function(info) {
			
				// 更新提示内容
				if(is_toast === undefined){
					uni.showToast({duration:3000,
						title: `上传中: ${Math.floor(info.percent * 100)}%`,
						icon: 'loading',
						duration: 10000, // 继续显示提示
						mask: true
					});
				}
				
			}
		}, function(err, data) {
			
			if(is_toast === undefined){
				uni.hideToast()
			}
			
			if (err) {
				console.log('上传失败',err);
				reject(err)
			} else {
				console.log('上传成功', data,store.state.oss_url + key);
				resolve({
					name: originalFileName,
					url: store.state.oss_url + '/' + key
				})
			}
		});
	})
}

export const ossDel = (url) => {
	let fileUrl = url.replace(store.state.ossurl,'')
	return new Promise((resolve,reject) => {
		// 删除文件
		cos.deleteObject({
		  Bucket,
		  Region,
		  Key: prefix + fileUrl
		}, function(err, data) {
		  if (err) {
		    console.error('删除文件失败:', err);
			reject()
		  } else {
		    console.log('文件删除成功:', data);
			resolve()
		  }
		});
	})
	
}